package co.salehi.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import co.salehi.domain.Operator;
import co.salehi.util.Util;

@RooWebScaffold(path = "operators", formBackingObject = Operator.class)
@RequestMapping("/operators")
@Controller
public class OperatorController {

	@RequestMapping(params = "form", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	public String createForm(Model uiModel) {
		uiModel.addAttribute("operator", new Operator());
		return "operators/create";
	}

	@RequestMapping(params = "oldPwd", method = RequestMethod.PUT)
	public String changePass(Operator operator, BindingResult bindingResult,
			Model uiModel, HttpServletRequest request) {
		User user = (User) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();

		Operator loggedInPerson = (Operator) Operator.findOperator(user
				.getUsername());

		String oldPass = request.getParameter("oldPwd");
		String newPassword = request.getParameter("password");
		String newPassword2 = request.getParameter("password2");
		if (!Util.toSHA256(oldPass).equals(loggedInPerson.getPassword())) {
			bindingResult.addError(new ObjectError("User",
					"Old Password is invalid"));
			return "operators/changePass";
		} else if (!newPassword.equalsIgnoreCase(newPassword2)) {
			bindingResult.addError(new ObjectError("User",
					"New Passwords Don't match"));
			return "operators/changePass";
		}
		loggedInPerson.setPassword(newPassword);
		// password2 must be set for validation
		loggedInPerson.setPassword2(newPassword);
		loggedInPerson.merge();
		return "redirect:/passwordChanged";
	}

	@RequestMapping(params = "changePass", method = RequestMethod.GET)
	public String changePassForm(Model uiModel) {
		uiModel.addAttribute("operator", new Operator());
		return "operators/changePass";
	}
	
    @RequestMapping(method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String create(@Valid Operator operator, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("operator", operator);
            return "operators/create";
        }
        uiModel.asMap().clear();
        operator.persist();
        return "redirect:/operators/" + encodeUrlPathSegment(operator.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("operator", Operator.findOperator(id));
        uiModel.addAttribute("itemId", id);
        return "operators/show";
    }
    
    @RequestMapping(method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            uiModel.addAttribute("operators", Operator.findOperatorEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) Operator.countOperators() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("operators", Operator.findAllOperators());
        }
        return "operators/list";
    }
    
    @RequestMapping(method = RequestMethod.PUT)
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String update(@Valid Operator operator, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("operator", operator);
            return "operators/update";
        }
        uiModel.asMap().clear();
        operator.merge();
        return "redirect:/operators/" + encodeUrlPathSegment(operator.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("operator", Operator.findOperator(id));
        return "operators/update";
    }
    
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Operator.findOperator(id).remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/operators";
    }


}
